package xyz.yq56.easytool.utils.lottery;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.commons.collections4.CollectionUtils;

import xyz.yq56.easytool.model.Award;
import xyz.yq56.easytool.utils.collection.CollectUtil;

/**
 * 抽奖工具类
 *
 * @author yi qiang
 * @date 2021/12/5 2:11
 */
public class LotteryUtil {

    private LotteryUtil() {
    }

    /**
     * 抽奖逻辑
     * <br> 输入奖励配置,则会按配置权重抽取1项
     *
     * @param awardList
     * @param <T>
     * @return
     */
    public static <T> T draw(List<Award<T>> awardList) {
        if (CollectionUtils.isEmpty(awardList)) {
            return null;
        }
        List<T> list = new ArrayList<>(128);
        for (Award<T> award : awardList) {
            int weight = award.getWeight();
            for (int i = 0; i < weight; i++) {
                if (award.getT() != null) {
                    list.add(award.getT());
                }
            }
        }
        return list.get(ThreadLocalRandom.current().nextInt(CollectUtil.size(list)));
    }


}
